import {
	defineConfig
} from 'vite';

import uni from '@dcloudio/vite-plugin-uni';
import inject from '@rollup/plugin-inject';

import xi_class from './xi-class.js';

let mode = 2; //0：网页模式 1：本地小程序模式 2：小程序模式

let host = '';
let server = 'https://chejian.wxqiandao.com';

let port = 1103;

let $define = {
	'__HOST__': '',
	'__API__': '/api',
	'__APP__': '/applet',
	'__ROOT__': '/files/applet',
}

if (mode == 0) {
	$define.__ROOT__ = host + '/files/applet'
} else if (mode == 1) {
	$define.__HOST__ = host
	$define.__API__ = ''
	$define.__ROOT__ = '/pages'
} else if (mode == 2) {
	$define.__HOST__ = server
	$define.__ROOT__ = server + '/files/applet'
}

export default defineConfig({
	plugins: [
		xi_class(),
		{
			name: "transform-xi",
			transform: function(src, path) {
				//添加组件name
				if (path.endsWith('.vue')) {
					const allow_path = [
						'src/views/',
					];
					if (allow_path.some(p => path.substr(__dirname.length + 1).startsWith(p))) {
						if (src.indexOf('defineOptions') === -1) {
							src = src.replace(/<script\s+setup>/g,
								'<script setup>');
						}
					}
				}
				//判断是vue文件和js文件和css文件
				if (path.indexOf('.vue') > -1 || path.indexOf('.js') > -1 || path.indexOf('.css') > -
					1) {
					//替换__DIR__为当前文件目录
					return {
						code: src
							.replaceAll('__HOST__', $define.__HOST__)
							.replaceAll('__API__', $define.__API__)
							.replaceAll('__APP__', $define.__APP__)
							.replaceAll('__ROOT__', $define.__ROOT__)
							.replaceAll('__DIR__', $define.__ROOT__ + path.substring(__dirname.length +
								6, path.lastIndexOf('/')))
							// .replaceAll('__DIR__', '.')
							.replaceAll('__IMG__', $define.__ROOT__ + path.substring(__dirname.length +
								6, path.indexOf('.')) + '/img')

							,
						map: null,
					};
				}
				return {
					code: src,
					map: null,
				};
			},
		},
		uni(),
		inject({
			Vue: ['/lib/inject.js', 'default'],
			xaoi: ['/lib/xaoi.js', 'default'],
			$post: ['/lib/api.js', 'post'],
			$conf: ['/lib/inject.js', 'conf'],
			$route: ['/lib/inject.js', 'conf'],
		}),
	],
	server: {
		host: "0.0.0.0",
		port: port,
		open: false,
		proxy: {
			'/api/': {
				target: mode == 2 ? server : host,
				changeOrigin: true,
				rewrite: (path) => path.replace(/^\/api/, '')
			},
			'/upload/': mode == 2 ? server : host,
			'/files/': mode == 2 ? server : host,
		},
	},
});